package org.ciallo.simplemusicplayer.dialog;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.divider.MaterialDivider;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongOptionsAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.service.MediaPlayerService;
import org.ciallo.simplemusicplayer.util.Constants;
import org.ciallo.simplemusicplayer.util.RingtoneUtil;
import org.ciallo.simplemusicplayer.util.TimeUtil;
import org.ciallo.simplemusicplayer.viewmodel.FavoritesViewModel;
import org.ciallo.simplemusicplayer.viewmodel.PlaylistViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SongViewModel;
import timber.log.Timber;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.ciallo.simplemusicplayer.dialog.PlayerSongDetailsDialogFragment.*;

/**
 * @author Jukomu
 * @Description: 歌曲的更多操作底部弹出对话框 (用于列表项)
 * @Package: org.ciallo.simplemusicplayer.dialog
 * @Project: SimpleMusicPlayer
 * @name: SongOptionsDialogFragment
 * @Date: 2025/5/31-00:47
 * @Filename: SongOptionsDialogFragment
 */
public class SongOptionsDialogFragment extends BottomSheetDialogFragment {
    public static final String TAG = "SongOptionsDialogFragment";
    private static final String ARG_SONG_ID = "arg_song_id";
    private static final String ARG_PLAYLIST_ID_CONTEXT = "arg_playlist_id_context";

    private long songIdToOperate = Constants.INVALID_INDEX; // 初始化为无效值
    private long playlistIdContext = Constants.INVALID_INDEX;

    private RecyclerView recyclerViewOptions;
    private SongOptionsAdapter optionsAdapter;
    private TextView tvDialogTitle;
    private MaterialDivider titleDivider;

    private SharedViewModel sharedViewModel;
    private FavoritesViewModel favoritesViewModel;
    private PlaylistViewModel playlistViewModel; // 用于添加到歌单和从歌单移除
    private SongViewModel songViewModel;     // 用于获取被操作歌曲的详细信息

    private Song songBeingOperated; // 被操作的歌曲对象

    // 定义操作项的唯一ID
    private static final int OPTION_ID_PLAY_IMMEDIATELY = 100;
    private static final int OPTION_ID_PLAY_NEXT = 101;
    private static final int OPTION_ID_ADD_TO_QUEUE_END = 102;
    private static final int OPTION_ID_FAVORITE_TOGGLE = 103;
    private static final int OPTION_ID_ADD_TO_PLAYLIST = 104;
    private static final int OPTION_ID_REMOVE_FROM_PLAYLIST = 105;
    private static final int OPTION_ID_SONG_DETAILS_INFO = 106;
    private static final int OPTION_ID_DELETE_FROM_DEVICE = 107;
    private static final int OPTION_ID_SET_AS_RINGTONE = 108;


    /**
     * 创建实例的工厂方法。
     * @param songId 要操作的歌曲ID。
     * @return 新的 SongOptionsDialogFragment 实例。
     */
    public static SongOptionsDialogFragment newInstance(long songId) {
        SongOptionsDialogFragment fragment = new SongOptionsDialogFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_SONG_ID, songId);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 创建实例的工厂方法 (当从歌单上下文中调用时)。
     * @param songId            要操作的歌曲ID。
     * @param playlistIdContext 所在的歌单ID，用于显示“从歌单移除”。
     * @return 新的 SongOptionsDialogFragment 实例。
     */
    public static SongOptionsDialogFragment newInstanceForPlaylist(long songId, long playlistIdContext) {
        SongOptionsDialogFragment fragment = new SongOptionsDialogFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_SONG_ID, songId);
        args.putLong(ARG_PLAYLIST_ID_CONTEXT, playlistIdContext);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            songIdToOperate = getArguments().getLong(ARG_SONG_ID, Constants.INVALID_INDEX);
            playlistIdContext = getArguments().getLong(ARG_PLAYLIST_ID_CONTEXT, Constants.INVALID_INDEX);
        }

        if (songIdToOperate == Constants.INVALID_INDEX) {
            Timber.e("SongOptionsDialogFragment created without a valid songId. Dismissing.");
            // 提前 dismiss，避免后续问题
            if (isAdded()) { // 确保Fragment已附加到Activity
                dismissAllowingStateLoss();
            }
            return; // 提前返回，不执行后续的ViewModel初始化
        }

        // 初始化ViewModels (现在这些ViewModel应该使用 requireActivity() 来共享，除非特定需要与Dialog生命周期绑定)
        sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        favoritesViewModel = new ViewModelProvider(requireActivity()).get(FavoritesViewModel.class); // 与Activity共享
        favoritesViewModel = new ViewModelProvider(requireActivity()).get(FavoritesViewModel.class); // 与Activity共享
        songViewModel = new ViewModelProvider(this).get(SongViewModel.class); // 可以与DialogFragment生命周期绑定
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        // 注意：不要在这里过早地访问或操作视图相关的逻辑，尤其是调用 getViewLifecycleOwner()
        // 视图的初始化和LiveData的观察应该在 onCreateView 或 onViewCreated 中进行。
        // onCreateDialog 主要用于创建对话框本身和设置其基本属性。
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局
        return inflater.inflate(R.layout.dialog_song_options, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (songIdToOperate == Constants.INVALID_INDEX) {
            // 如果在onCreate中已经处理了无效songId并dismiss，这里可能不需要再次检查
            // 但作为防御，可以再次判断
            if(isAdded()) dismissAllowingStateLoss();
            return;
        }

        // 初始化视图控件
        tvDialogTitle = view.findViewById(R.id.textView_song_options_dialog_title);
        titleDivider = view.findViewById(R.id.divider_song_options_title);
        recyclerViewOptions = view.findViewById(R.id.recyclerView_options);

        // 设置RecyclerView和加载数据现在在这里进行
        setupRecyclerView();
        loadAndObserveSongDetails();

        // 设置BottomSheet行为 (可以在这里或 onCreateDialog 中，但确保 Dialog 对象已创建)
        Dialog dialog = getDialog();
        if (dialog instanceof BottomSheetDialog) {
            BottomSheetBehavior<?> bottomSheetBehavior = ((BottomSheetDialog) dialog).getBehavior();
            if (bottomSheetBehavior != null) {
                view.post(() -> { // 确保在视图测量后
                    int maxHeight = (int) (getResources().getDisplayMetrics().heightPixels * 0.70);
                    ViewGroup.LayoutParams params = view.getLayoutParams();
                    if (params == null) { // 如果视图是通过 setContentView 设置的，它可能没有直接的 LayoutParams
                        View sheet = dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
                        if (sheet != null) {
                            params = sheet.getLayoutParams();
                        }
                    }
                    if (params != null) {
                        if (view.getHeight() > maxHeight) { // 检查的是包含内容的view高度
                            params.height = maxHeight;
                            view.setLayoutParams(params);
                        }
                    }
                    bottomSheetBehavior.setPeekHeight(maxHeight); // 可以同时设置PeekHeight
                });
                bottomSheetBehavior.setSkipCollapsed(true);
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        }
    }

    /**
     * 加载并观察被操作歌曲的详细信息。
     * 这个方法现在在 onViewCreated 中调用，以确保 getViewLifecycleOwner() 可用。
     */
    private void loadAndObserveSongDetails() {
        // 使用 getViewLifecycleOwner()，因为它在 onViewCreated 之后是有效的
        songViewModel.getSongById(songIdToOperate).observe(getViewLifecycleOwner(), song -> {
            if (song != null) {
                songBeingOperated = song;
                tvDialogTitle.setText(String.format("歌曲：%s", song.getTitle()));
                tvDialogTitle.setVisibility(View.VISIBLE);
                titleDivider.setVisibility(View.VISIBLE);
                buildAndSubmitOptionsList(); // 根据歌曲信息构建操作列表
            } else {
                Timber.e("Song with ID %d not found in database.", songIdToOperate);
                Toast.makeText(getContext(), "无法加载歌曲信息", Toast.LENGTH_SHORT).show();
                tvDialogTitle.setText("歌曲信息加载失败");
                tvDialogTitle.setVisibility(View.VISIBLE);
                titleDivider.setVisibility(View.GONE);
                if(optionsAdapter != null) optionsAdapter.submitList(createCloseOnlyOption());
            }
        });
    }

    private void setupRecyclerView() {
        // Adapter 现在在 buildAndSubmitOptionsList 之外创建，只设置 LayoutManager
        recyclerViewOptions.setLayoutManager(new LinearLayoutManager(getContext()));
        // 创建 Adapter 实例，只需要传递 listener
        optionsAdapter = new SongOptionsAdapter(this::handleOptionClick); // 使用方法引用
        recyclerViewOptions.setAdapter(optionsAdapter);
    }

    /**
     * 根据当前歌曲状态构建操作项列表，并提交给Adapter。
     */
    private void buildAndSubmitOptionsList() {
        if (songBeingOperated == null || getContext() == null) {
            if (optionsAdapter != null) optionsAdapter.submitList(createCloseOnlyOption());
            return;
        }

        List<SongOptionsAdapter.OptionItem> options = new ArrayList<>();

        // 新增 "立即播放"
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_PLAY_IMMEDIATELY, "立即播放", R.drawable.ic_play_now, true, true)); // 需要 ic_play_now
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_PLAY_NEXT, "下一首播放", R.drawable.ic_play_next_song, true, true));
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_ADD_TO_QUEUE_END, "添加到播放队列", R.drawable.ic_add_to_queue, true, true));
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_FAVORITE_TOGGLE, getString(R.string.song_option_favorite), R.drawable.ic_favorite_border, true, true));
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_ADD_TO_PLAYLIST, getString(R.string.player_add_to_playlist), R.drawable.ic_playlist_add, true, true));

        boolean showRemoveFromPlaylist = (playlistIdContext != Constants.INVALID_INDEX);
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_REMOVE_FROM_PLAYLIST, "从当前歌单移除", R.drawable.ic_remove_from_queue, showRemoveFromPlaylist, showRemoveFromPlaylist));

        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_SET_AS_RINGTONE, getString(R.string.player_set_as_ringtone), R.drawable.ic_ringtone, true, true)); // 加回设为铃声
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_SONG_DETAILS_INFO, "歌曲信息", R.drawable.ic_info_about, true, true));
        options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_DELETE_FROM_DEVICE, "从设备删除", R.drawable.ic_delete_sweep, true, true));

        if (optionsAdapter != null) {
            List<SongOptionsAdapter.OptionItem> visibleOptions = new ArrayList<>();
            for (SongOptionsAdapter.OptionItem option : options) {
                if (option.isVisible) visibleOptions.add(option);
            }
            optionsAdapter.submitList(visibleOptions);
        }
        updateFavoriteOptionItem();
    }

    /**
     * 处理操作项的点击事件。
     * @param item 被点击的操作项。
     */
    private void handleOptionClick(SongOptionsAdapter.OptionItem item) {
        if (songBeingOperated == null) { // 移除了对 item.id != OPTION_ID_CLOSE 的检查，因为关闭按钮不在这个列表里了
            Toast.makeText(getContext(), "歌曲信息无效", Toast.LENGTH_SHORT).show();
            dismiss();
            return;
        }

        boolean shouldDismiss = true; // 默认操作后关闭对话框

        switch (item.id) {
            case OPTION_ID_PLAY_IMMEDIATELY:
                if (sharedViewModel != null) sharedViewModel.playImmediately(songBeingOperated);
                Toast.makeText(getContext(), "即将播放: " + songBeingOperated.getTitle(), Toast.LENGTH_SHORT).show();
                break;
            case OPTION_ID_PLAY_NEXT:
                if (sharedViewModel != null) sharedViewModel.insertSongAsNext(songBeingOperated);
                Toast.makeText(getContext(), "\"" + songBeingOperated.getTitle() + "\" 已添加到下一首播放", Toast.LENGTH_SHORT).show();
                break;
            case OPTION_ID_ADD_TO_QUEUE_END:
                if (sharedViewModel != null) sharedViewModel.addSongToEndOfQueue(songBeingOperated);
                Toast.makeText(getContext(), "\"" + songBeingOperated.getTitle() + "\" 已添加到播放队列末尾", Toast.LENGTH_SHORT).show();
                break;
            case OPTION_ID_FAVORITE_TOGGLE:
                toggleFavoriteStatus(songBeingOperated);
                shouldDismiss = false; // 收藏操作不立即关闭，等待UI通过LiveData更新
                break;
            case OPTION_ID_ADD_TO_PLAYLIST:
                if (getParentFragmentManager() != null) { // 确保 FragmentManager 可用
                    AddToPlaylistDialogFragment.newInstance(songBeingOperated.getId())
                            .show(getParentFragmentManager(), AddToPlaylistDialogFragment.TAG);
                } else {
                    Toast.makeText(getContext(), "无法打开添加到歌单对话框", Toast.LENGTH_SHORT).show();
                }
                shouldDismiss = false; // 不立即关闭当前对话框
                break;
            case OPTION_ID_REMOVE_FROM_PLAYLIST:
                if (playlistIdContext != Constants.INVALID_INDEX && playlistViewModel != null) {
                    playlistViewModel.removeSongFromPlaylist(playlistIdContext, songBeingOperated.getId());
                    Toast.makeText(getContext(), "已从歌单移除", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getContext(), "非歌单上下文，无法移除", Toast.LENGTH_SHORT).show();
                }
                break;
            case OPTION_ID_SET_AS_RINGTONE: // 加回设为铃声
                showSetAsRingtoneDialog(songBeingOperated);
                // 这个对话框自己会dismiss，或者在成功/失败后决定
                shouldDismiss = false; // 外部对话框不立即关闭
                break;
            case OPTION_ID_SONG_DETAILS_INFO:
                showSongInfoDialogInternal(songBeingOperated);
                shouldDismiss = false; // 查看信息不关闭主操作对话框
                break;
            case OPTION_ID_DELETE_FROM_DEVICE:
                confirmAndDeleteSongFromDevice(songBeingOperated);
                shouldDismiss = false; // 等待确认对话框的结果
                break;
        }

        if (shouldDismiss) {
            dismiss();
        }
    }

    /**
     * 动态更新收藏/取消收藏的选项UI。
     * 这个方法现在需要找到在 submitList 提交的 (可能已过滤的) 列表中的收藏项，并通知更新。
     */
    private void updateFavoriteOptionItem() {
        if (favoritesViewModel == null || optionsAdapter == null || songBeingOperated == null || !isAdded() || getView() == null) return;

        // 观察收藏状态 LiveData
        favoritesViewModel.isFavorite(songBeingOperated.getId()).observe(getViewLifecycleOwner(), isFavorite -> {
            if (!isAdded() || getContext() == null) return;

            // 更新提交给 Adapter 的数据源 (options 列表) 中对应项的文本和图标
            // 找到原始 options 列表（或当前 Adapter 持有的列表的一个副本）中的收藏项
            List<SongOptionsAdapter.OptionItem> currentAdapterList = optionsAdapter.getCurrentList();
            int favItemPositionInAdapter = -1;
            SongOptionsAdapter.OptionItem favItemToUpdate = null;

            for (int i = 0; i < currentAdapterList.size(); i++) {
                if (currentAdapterList.get(i).id == OPTION_ID_FAVORITE_TOGGLE) {
                    favItemToUpdate = currentAdapterList.get(i); // 这是Adapter当前持有的对象
                    favItemPositionInAdapter = i;
                    break;
                }
            }

            if (favItemToUpdate != null) {
                boolean newIsFavorite = (isFavorite != null && isFavorite);
                String newText = newIsFavorite ? getString(R.string.song_option_unfavorite) : getString(R.string.song_option_favorite);
                int newIconRes = newIsFavorite ? R.drawable.ic_favorite_filled : R.drawable.ic_favorite_border;

                // 检查文本或图标是否有实际变化，避免不必要的 notifyItemChanged
                if (!Objects.equals(favItemToUpdate.text, newText) || favItemToUpdate.iconResId != newIconRes) {
                    favItemToUpdate.setText(newText);
                    favItemToUpdate.setIconResId(newIconRes);
                    if (favItemPositionInAdapter != -1) {
                        optionsAdapter.notifyItemChanged(favItemPositionInAdapter);
                    }
                }
            } else {
                Timber.w("Favorite option item not found in adapter's current list for UI update.");
            }
        });
    }

    private void addSongToPlayNext(Song song) {
        if (sharedViewModel == null) return;
        MediaPlayerService.PlaybackInfo currentPlayback = sharedViewModel.playbackInfo.getValue();
        List<Song> newQueue;
        int playNextIndex;

        if (currentPlayback != null && currentPlayback.activeQueue != null && !currentPlayback.activeQueue.isEmpty()) {
            newQueue = new ArrayList<>(currentPlayback.activeQueue); // 基于当前活动队列
            int currentPlayingOriginalIndex = Constants.INVALID_INDEX;

            // 找到当前播放歌曲在 newQueue (即 activeQueue 副本) 中的位置
            if (currentPlayback.song != null) {
                for (int i = 0; i < newQueue.size(); i++) {
                    if (newQueue.get(i).getId() == currentPlayback.song.getId()) {
                        currentPlayingOriginalIndex = i;
                        break;
                    }
                }
            }
            // 移除可能已存在的副本
            newQueue.removeIf(s -> s.getId() == song.getId());

            playNextIndex = (currentPlayingOriginalIndex == Constants.INVALID_INDEX) ? 0 : currentPlayingOriginalIndex + 1;
            if (playNextIndex > newQueue.size()) playNextIndex = newQueue.size(); // 放到末尾
            newQueue.add(playNextIndex, song);

        } else { // 如果当前没有播放队列或队列为空
            newQueue = new ArrayList<>();
            newQueue.add(song);
            playNextIndex = 0; // 新队列，从0开始
        }
        // 使用 playSongAtIndex，它会设置新的原始队列并从指定索引播放
        // 注意：这会重置 Service 中的 originalPlayQueue 和 shuffledPlayQueue
        sharedViewModel.playSongAtIndex(newQueue, playNextIndex);
        Toast.makeText(getContext(), "\"" + song.getTitle() + "\" 已添加到下一首播放", Toast.LENGTH_SHORT).show();
    }

    private void addSongToQueueEnd(Song song) {
        if (sharedViewModel == null) return;
        MediaPlayerService.PlaybackInfo currentPlayback = sharedViewModel.playbackInfo.getValue();
        List<Song> newQueue;
        int currentIndexToMaintain = Constants.INVALID_INDEX;

        if (currentPlayback != null && currentPlayback.activeQueue != null && !currentPlayback.activeQueue.isEmpty()) {
            newQueue = new ArrayList<>(currentPlayback.activeQueue);
            // 移除可能已存在的副本
            boolean removed = newQueue.removeIf(s -> s.getId() == song.getId());
            newQueue.add(song); // 添加到末尾

            // 确定当前播放的歌曲在新队列中的索引，以保持播放不中断 (如果被移除的不是当前歌曲)
            if (currentPlayback.song != null) {
                for (int i = 0; i < newQueue.size(); i++) {
                    if (newQueue.get(i).getId() == currentPlayback.song.getId()) {
                        currentIndexToMaintain = i;
                        break;
                    }
                }
                if(currentIndexToMaintain == Constants.INVALID_INDEX && !removed && !newQueue.isEmpty()){ // 如果当前歌曲还在，但由于添加导致索引可能变化
                    //通常Service的currentQueueIndex是基于originalPlayQueue的，这里需要小心
                    //最简单的是不改变当前播放的索引，让Service的ACTION_SET_PLAY_QUEUE处理
                    currentIndexToMaintain = currentPlayback.song != null ? findSongIndexInList(newQueue, currentPlayback.song.getId()) : 0;
                }
            }


        } else {
            newQueue = new ArrayList<>();
            newQueue.add(song);
            currentIndexToMaintain = 0;
        }
        // 发送 ACTION_SET_PLAY_QUEUE 更新队列，但不立即强制播放新歌
        Intent intent = new Intent(getContext(), MediaPlayerService.class);
        intent.setAction(Constants.ACTION_SET_PLAY_QUEUE);
        intent.putParcelableArrayListExtra(Constants.EXTRA_PLAY_QUEUE, new ArrayList<>(newQueue));
        intent.putExtra(Constants.EXTRA_START_INDEX, currentIndexToMaintain != Constants.INVALID_INDEX ? currentIndexToMaintain : 0); // 传递正确的索引
        requireContext().startService(intent);

        Toast.makeText(getContext(), "\"" + song.getTitle() + "\" 已添加到播放队列", Toast.LENGTH_SHORT).show();
    }
    private int findSongIndexInList(List<Song> queue, long songId){
        for(int i=0; i<queue.size(); i++){
            if(queue.get(i).getId() == songId){
                return i;
            }
        }
        return Constants.INVALID_INDEX;
    }


    private void toggleFavoriteStatus(Song song) {
        if (favoritesViewModel == null || song == null || getViewLifecycleOwner() == null || !isAdded()) {
            return;
        }
        final long songId = song.getId();

        // 观察 LiveData 以获取当前状态，然后立即行动并停止进一步观察这个特定实例
        LiveData<Boolean> liveDataIsFavorite = favoritesViewModel.isFavorite(songId);

        liveDataIsFavorite.observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean isCurrentlyFavorite) {
                // 一旦收到值，就移除这个观察者，避免因后续的数据库操作再次触发它
                liveDataIsFavorite.removeObserver(this);

                if (!isAdded() || getContext() == null) {
                    return;
                }

                // 后续逻辑与之前相同
                if (isCurrentlyFavorite != null) {
                    if (isCurrentlyFavorite) {
                        favoritesViewModel.removeFromFavorites(songId);
                        Toast.makeText(getContext(), getString(R.string.unfavorited_toast_message, song.getTitle()), Toast.LENGTH_SHORT).show();
                    } else {
                        favoritesViewModel.addToFavorites(songId);
                        Toast.makeText(getContext(), getString(R.string.favorited_toast_message, song.getTitle()), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    favoritesViewModel.addToFavorites(songId); // 默认为添加
                    Toast.makeText(getContext(), getString(R.string.favorited_toast_message, song.getTitle()), Toast.LENGTH_SHORT).show();
                }
                // 真正的UI更新（按钮文本/图标）将由 updateFavoriteOptionItem 中的持久观察者处理
            }
        });
    }


    private void showSetAsRingtoneDialog(Song songToSet) {
        // (代码与 PlayerSongDetailsDialogFragment 中的一致，复用 RingtoneUtil)
        if (getContext() == null) return;
        final String[] types = {"来电铃声", "通知铃声", "闹钟铃声"};
        final int[] ringtoneTypes = {
                android.media.RingtoneManager.TYPE_RINGTONE,
                android.media.RingtoneManager.TYPE_NOTIFICATION,
                android.media.RingtoneManager.TYPE_ALARM
        };
        new AlertDialog.Builder(requireContext())
                .setTitle("设为铃声")
                .setItems(types, (dialog, which) -> {
                    if (RingtoneUtil.canWriteSettings(requireContext())) {
                        RingtoneUtil.setRingtone(requireContext(), songToSet, ringtoneTypes[which]);
                    } else {
                        RingtoneUtil.requestWriteSettingsPermission(requireContext());
                    }
                    dismiss();
                })
                .setNegativeButton(R.string.cancel, (d,w) -> dismiss())
                .show();
    }

    private void showSongInfoDialogInternal(Song song) {
        // (代码与 PlayerSongDetailsDialogFragment 中的一致)
        if (getContext() == null) return;
        StringBuilder infoBuilder = new StringBuilder();
        infoBuilder.append("标题: ").append(song.getTitle()).append("\n");
        infoBuilder.append("歌手: ").append(song.getArtistName()).append("\n");
        infoBuilder.append("专辑: ").append(song.getAlbumName()).append("\n");
        infoBuilder.append("时长: ").append(TimeUtil.formatDuration(song.getDuration())).append("\n");
        infoBuilder.append("路径: ").append(song.getPath()).append("\n");
        infoBuilder.append("大小: ").append(PlayerSongDetailsDialogFragment.formatFileSize(song.getSize())).append("\n"); // 复用格式化方法
        if (song.getMimeType() != null) infoBuilder.append("格式: ").append(song.getMimeType()).append("\n");
        if (song.getYear() > 0) infoBuilder.append("年份: ").append(song.getYear()).append("\n");

        new AlertDialog.Builder(requireContext())
                .setTitle("歌曲信息")
                .setMessage(infoBuilder.toString())
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void confirmAndDeleteSongFromDevice(Song song) {
        if (getContext() == null || song == null || song.getPath() == null) return;
        new AlertDialog.Builder(requireContext())
                .setTitle("删除歌曲")
                .setMessage("确定要从设备上删除歌曲 \"" + song.getTitle() + "\" 吗？\n此操作也会将其从本地音乐库和所有歌单中移除，且不可撤销。")
                .setPositiveButton("全部删除", (dialog, which) -> {
                    File fileToDelete = new File(song.getPath());
                    boolean deletedFileSuccessfully = false;
                    if (fileToDelete.exists()) {
                        if (fileToDelete.delete()) {
                            deletedFileSuccessfully = true;
                            Timber.i("Song file deleted from device: %s", song.getPath());
                            // 还可以通知系统媒体扫描器更新该文件状态 (可选)
                            // MediaScannerConnection.scanFile(requireContext(), new String[]{song.getPath()}, null, null);
                        } else {
                            Timber.e("Failed to delete song file from device: %s", song.getPath());
                        }
                    } else {
                        Timber.w("Song file to delete not found on disk: %s. Proceeding with DB removal.", song.getPath());
                        deletedFileSuccessfully = true; // 视为文件层面已“处理”或“不存在”
                    }

                    // 从数据库中删除该歌曲记录 (这将通过CASCADE级联删除收藏和歌单关联)
                    if (songViewModel != null) {
                        songViewModel.deleteSongFromDatabase(song.getId()); // <--- 调用 ViewModel 的方法
                    }

                    // 从当前播放服务的队列中移除 (如果存在)
                    if (sharedViewModel != null) {
                        sharedViewModel.removeSongFromQueue(song.getId());
                    }

                    String toastMessage = deletedFileSuccessfully ? "歌曲已从设备和本地库删除" : "删除歌曲文件失败，但已从本地库移除";
                    Toast.makeText(getContext(), toastMessage, Toast.LENGTH_LONG).show();
                    dismiss(); // 关闭对话框
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    /**
     * 创建一个只包含“关闭”选项的列表。
     * @return 只包含关闭操作的列表。
     */
    private List<SongOptionsAdapter.OptionItem> createCloseOnlyOption() {
        List<SongOptionsAdapter.OptionItem> options = new ArrayList<>();
        if (getContext() != null) { // 确保 Context 有效以获取字符串资源
            // 假设你有一个关闭图标 R.drawable.ic_close (如果没有，可以使用 null 或 0)
            // options.add(new SongOptionsAdapter.OptionItem(OPTION_ID_CLOSE, "关闭", R.drawable.ic_close_small, true, true));
            // 如果不希望有关闭按钮，返回空列表，对话框可以通过点击外部或返回键关闭
        }
        return options; // 返回空列表，让对话框可以被外部点击或返回键关闭
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
